<template>
    <div class="p-15 p-t-0 box-shadow-1">
        <div class="table-padding orderDialog">
            <div>
                <el-form>
                    <el-row :gutter="24">
                        <el-col :span="6">
                            <div class="el-input el-input-group el-input-group--prepend">
                                <div class="el-input-group__prepend">供应商</div>
                                <el-select class="w-100p" v-model="supplier" placeholder="请选择供应商"
                                           :disabled="true" >
                                    <el-option
                                            v-for="item in suppliers"
                                            :key="item.id"
                                            :label="item.name"
                                            :value="item.id">
                                    </el-option>
                                </el-select>
                            </div>
                        </el-col>
                        <!--<el-col :span="6">-->
                            <!--<div class="el-input el-input-group el-input-group&#45;&#45;prepend">-->
                                <!--<div class="el-input-group__prepend">经办人</div>-->
                                <!--<el-select class="w-100p" v-model="purchaser" placeholder="请选择经办人" >-->
                                    <!--<el-option-->
                                            <!--v-for="item in purchasers"-->
                                            <!--:key="item.id"-->
                                            <!--:label="item.name"-->
                                            <!--:value="item.id">-->
                                    <!--</el-option>-->
                                <!--</el-select>-->
                            <!--</div>-->
                        <!--</el-col>-->
                        <el-col :span="6">
                            <el-input type="text" v-model="amountSum" @focus="printNum($event)" style="width:100%" auto-complete="off" placeholder="请输入本次付款金额"  @blur="isNumValue($event);changeMoney(amountSum)">
                                <template slot="prepend">
                                    <el-button>本次付款金额</el-button>
                                </template>
                            </el-input>
                        </el-col>
                        <el-col :span="12">
                            <el-input type="text"
                                      v-model="remark"
                                      auto-complete="off"
                                      placeholder="请输入备注信息"
                                      class="w-100p">
                                <template slot="prepend">
                                    <el-button>备注</el-button>
                                </template>
                            </el-input>
                        </el-col>
                    </el-row>
                    <!--<el-row>&lt;!&ndash;:xl="8" :lg="8" :md="8" :sm="24" :xs="24" &ndash;&gt;
                        <el-col :span="8" style="text-align: left; margin-bottom: 10px">
                            <el-input type="text" v-model="amountSum" @focus="printNum($event)" style="width:100%" auto-complete="off" placeholder="请输入本次付款金额"  @blur="isNumValue($event);changeMoney(amountSum)">
                                <template slot="prepend">
                                    <el-button>本次付款金额</el-button>
                                </template>
                            </el-input>
                        </el-col>
                    </el-row>-->
                </el-form>
            </div>   <!--头部验证条件-->
            <div v-if="id == 1">
                <!--采购入库付款-->
                <!--按钮集-->
                <el-row class="m-t-15 m-b-15 text-left">
                    <el-col :span="6">
                        <el-button :disabled="canSave" class="el-button-my btn-success-2 m-l-0" type="danger" @click="submitForm()"><i class="icon f-14 icon-tijiao"></i> 提交</el-button>
                        <el-button class="el-button-my btn-danger m-l-0" type="success" @click="goBack()"><i class="icon f-16 icon-54"></i> 取消</el-button>
                    </el-col>
                </el-row>
                <div class="orderTable">
                    <el-table
                            :data="tableData"
                            border
                            show-summary
                            :summary-method="getSummaries"
                            style="width: 100%">
                        <el-table-column
                                type="index"
                                width="50">
                        </el-table-column>
                        <el-table-column
                                prop="inTime"
                                label="入库日期"
                        >
                        </el-table-column>
                        <el-table-column
                                prop="goodsStatus"
                                label="单据类型"
                        >
                            <template scope="scope">
                                <div>
                                    {{scope.row.type.text}}
                                </div>
                            </template>
                        </el-table-column>
                        <el-table-column
                                prop="no"
                                label="单据号"
                        >
                        </el-table-column>
                        <el-table-column
                                prop="amount"
                                label="总金额"
                        >
                        </el-table-column>
                        <el-table-column
                                prop="amount"
                                label="应付总金额"
                        >
                            <template scope="scope">
                                <div >
                                    {{scope.row.arrAmount}}
                                </div>
                            </template>
                        </el-table-column>
                        <el-table-column
                                prop="realamount"
                                label="本次付款金额"
                        >
                            <template scope="scope">
                                <div>
                                    <el-input class="nowidth bills" type="text" @focus="printNum($event)" style="float: left;width:100%" v-model="scope.row.realamount" @blur="isDouble(scope.row,'realamount');valideValue(scope.$index)">
                                        <!--<template slot="prepend" v-if="scope.row.goodsStatus.key=='PURCHASE'">-</template>
                                        <template slot="prepend" v-if="scope.row.goodsStatus.key=='RETURNGOODS'">+</template>-->
                                    </el-input>
                                </div>
                            </template>
                        </el-table-column>
                        <el-table-column
                                prop="youhuiamount"
                                label="本次优惠金额"
                        >
                            <template scope="scope">
                                <div>
                                    <el-input class="nowidth" type="text" @focus="printNum($event)" style="float: left;width:100%" v-model="scope.row.youhuiamount" @blur="isDouble(scope.row,'youhuiamount'); validYouhui(scope.$index)"></el-input>
                                    <span style="display: block; float: left;"></span>
                                </div>
                            </template>
                        </el-table-column>
                      <el-table-column
                        prop="remark"
                        label="备注"
                      >
                        <template scope="scope">
                          <div>
                            <el-input class="nowidth bills" type="text" style="float: left;width:100%" v-model="scope.row.remark" placeholder="请输入备注">
                              <!--<template slot="prepend" v-if="scope.row.goodsStatus.key=='PURCHASE'">-</template>
                              <template slot="prepend" v-if="scope.row.goodsStatus.key=='RETURNGOODS'">+</template>-->
                            </el-input>
                          </div>
                        </template>
                      </el-table-column>
                        <el-table-column
                                label="删除" width="70">
                            <template scope="scope">
                                <el-button  @click="handleDelete(scope.$index, scope.row)" type="text"  size="small"
                                            style="margin: 0px;">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </div><!--Table数据处理-->
            </div>

            <div v-if="id == 2">
                <!--采购退货收款-->
                <!--按钮集-->
                <el-row class="m-t-15 m-b-15 text-left">
                    <el-col :span="6">
                        <el-button class="el-button-my btn-success-2 m-l-0" type="danger" @click="submitForm()"><i class="icon f-14 icon-tijiao"></i> 提交</el-button>
                        <el-button class="el-button-my btn-danger m-l-0" type="success" @click="goBack()"><i class="icon f-16 icon-54"></i> 取消</el-button>
                    </el-col>
                </el-row>
                <div class="orderTable">
                    <el-table
                            :data="tableData"
                            border
                            show-summary
                            :summary-method="getSummaries"
                            style="width: 100%">
                        <el-table-column
                                type="index"
                                width="50">
                        </el-table-column>
                        <el-table-column
                                prop="createAt"
                                label="出库日期"
                        >
                          <template scope="scope">
                            <div>
                              {{scope.row.outTime}}
                            </div>
                          </template>
                        </el-table-column>
                        <el-table-column
                                prop="type"
                                label="单据类型"
                        >
                            <template scope="scope">
                                <div>
                                    {{scope.row.type.text}}
                                </div>
                            </template>
                        </el-table-column>
                        <el-table-column
                                prop="no"
                                label="单据号"
                        >
                        </el-table-column>
                      <el-table-column
                        prop="arrearAmount"
                        label="总金额"
                      >
                        <template scope="scope">
                          <div >
                            {{scope.row.amount}}
                          </div>
                        </template>
                      </el-table-column>
                        <el-table-column
                                prop="arrearAmount"
                                label="应退总金额"
                        >
                            <template scope="scope">
                                <div >
                                    {{scope.row.arrAmount}}
                                </div>
                            </template>
                        </el-table-column>
                        <el-table-column
                                prop="realamount"
                                label="本次退款金额"
                        >
                            <template scope="scope">
                                <div>
                                    <el-input class="nowidth bills" type="text" @focus="printNum($event)" style="float: left;width:100%" v-model="scope.row.realamount" @blur="isDouble(scope.row,'realamount');valideValue(scope.$index)">
                                        <!--<template slot="prepend" v-if="scope.row.goodsStatus.key=='PURCHASE'">-</template>
                                        <template slot="prepend" v-if="scope.row.goodsStatus.key=='RETURNGOODS'">+</template>-->
                                    </el-input>
                                </div>
                            </template>
                        </el-table-column>
                       <!-- <el-table-column
                                prop="youhuiamount"
                                label="优惠"
                        >
                            <template scope="scope">
                                <div>
                                    <el-input class="nowidth" type="text" @focus="printNum($event)" style="float: left;width:100%" v-model="scope.row.youhuiamount" @blur="isDouble(scope.row,'youhuiamount'); validYouhui(scope.$index)"></el-input>
                                    <span style="display: block; float: left;"></span>
                                </div>
                            </template>
                        </el-table-column>-->
                      <el-table-column
                        prop="remark"
                        label="备注"
                      >
                        <template scope="scope">
                          <div>
                            <el-input class="nowidth bills" type="text" style="float: left;width:100%" v-model="scope.row.remark" placeholder="请输入备注">
                              <!--<template slot="prepend" v-if="scope.row.goodsStatus.key=='PURCHASE'">-</template>
                              <template slot="prepend" v-if="scope.row.goodsStatus.key=='RETURNGOODS'">+</template>-->
                            </el-input>
                          </div>
                        </template>
                      </el-table-column>
                        <el-table-column
                                label="删除" width="70">
                            <template scope="scope">
                              <el-button  @click="handleDelete(scope.$index, scope.row)" type="text"  size="small"
                                          style="margin: 0px;">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </div><!--Table数据处理-->
            </div> <!--采购退货-->
        </div>
        <PluginConfirm
                :show="dialogIsShow"
                @chooseSure="chooseSure()"
                @chooseCancel="chooseCancel()"
                @dialogResult="dialogResult">
        </PluginConfirm>
    </div>
</template>
<script>
    //注意路径
    export default{
        data(){
            return {
                canSave:false,
                modelForm:{

                },
                supplier:"",//供应商
                purchaser:"",//经办人
                documentType:"",

                suppliers:[], //供应商
                purchasers:[],//经办人
                createAt_st:"",//开始日期
                createAt_et:"",//结束日期
                tableData:[],
                remark:"",
                documentTypes:[], //单据类型
                amountSum:0,
                id:'',
                dialogIsShow:false,
                curDataPkId:0,
                curDataIndex:0
            };
        },
        created(){
            window.this = this;
            if(this.$route.query.id){
                this.id=this.$route.query.id; //id =1 采购进货付款单 id=2 采购退货收货单
            }
            if(this.$route.query.s){
                this.supplier = parseInt(this.$route.query.s);
            }
            //console.log(this.$route.query.id);
            this.initData();
        },
        methods: {
        //页面第一次进来获取表单需要的数据
            initData(){
                var search = "flag=1";
                if(this.supplier){
                    search = "search.supplierId_eq="+this.supplier+"&"+search;
                }
                if(this.id==1){
                    search = "type=STOREIN&"+search;
                }else if(this.id==2){
                    search = "type=STOREOUT&"+search;
                }
                if(!search){
                    return;
                }
                this.$axios.get("stores/receivePayments/create?"+search).then(data=>{
                    if(data.status==200){
                        this.suppliers = data.content.suppliers;
                        this.documentTypes = data.content.receivePaymentTypes;
                        if(data.content.orders && data.content.orders.length>0){
                            for(let i=0;i<data.content.orders.length;i++){
                              data.content.orders[i].arrAmount= ((data.content.orders[i].amount*1)-(data.content.orders[i].payAmount*1)-(data.content.orders[i].giftAmount*1)).toFixed(2)
                                data.content.orders[i].realamount=0;
                                data.content.orders[i].youhuiamount=0
                            }
                        }
                        this.tableData = data.content.orders;

                    }else{
                        this.$message.error(data.message);
                    }
                })
            },
            goBack() {
                this.router.go(-1);
            },
            valideValue(index){
                if(this.tableData[index].youhuiamount*1>0){
                    if(this.tableData[index].arrAmount*1<(this.tableData[index].realamount*1+this.tableData[index].youhuiamount*1)){
                        this.$message({
                            type: 'warning',
                            message: '优惠金额与结算金额之和大于该单据应付金额!'
                        });
                        this.tableData[index].realamount = 0;
                    }
                }else {
                    if(this.tableData[index].arrAmount*1<this.tableData[index].realamount*1){
                        this.$message({
                            type: 'warning',
                            message: '输入金额大于该单据应付金额!'
                        });
                        this.tableData[index].realamount = 0;
                    }
                }

            },
            validYouhui(index){
                if(this.tableData[index].arrAmount*1<(this.tableData[index].realamount*1+this.tableData[index].youhuiamount*1)){
                    this.$message({
                        type: 'warning',
                        message: '优惠金额与结算金额之和大于该单据应付金额!'
                    });
                    if(this.tableData[index].realamount*1>0){
                        this.tableData[index].youhuiamount = 0;
                    }
                }
            },
            submitForm() {

                if (this.tableData == null || this.tableData.length == 0) {
                    this.$message.error("请添加单据明细！");
                    return;
                }
                for (var i = 0; i < this.tableData.length; i++) {
                    if(this.tableData[i].realamount==0 && !this.tableData[i].realamount){
                        this.$message.error("第"+(i+1)+"行没有填写结算金额");
                        return;
                    }
                }

                var data = {};
                this.modelForm = {
                    supplierId:this.supplier,
                    remark:this.remark,
                   type:this.id==1?'STOREIN':'STOREOUT'
                };


                for(var i=0;i<this.suppliers.length;i++){
                  if(this.modelForm.supplierId==this.suppliers[i].id){
                    this.modelForm.supplierName=this.suppliers[i].name;
                  }
                }
                var details=[];
                for(var i=0;i<this.tableData.length;i++){
                  details.push({
                    id:this.tableData[i].id,
                    orderNo:this.tableData[i].no,
                    orderAmount:this.tableData[i].amount,
                    amount:this.tableData[i].realamount,
                    giftAmount:this.tableData[i].youhuiamount,
                    remark:this.tableData[i].remark
                  })
                }
              data.order = this.modelForm;
              data.details = details;
              console.log(data);
                if(this.canSave){
                    return;
                }
                this.canSave = true;
                this.$axios.post("stores/receivePayments/create",data,"json").then(data=>{
                    this.canSave = false;
                    if(data.status==200){
                        this.$message.success(data.message);
                        this.router.go(-1);
                    }else{
                        this.$message.error(data.message);
                    }
                });


            },

            resetForm(formName) {
                this.$refs[formName].resetFields();
            },
            isNum(item,key){
                //console.log(item);
                //console.log(key);
                var r = /^\+?[1-9][0-9]*$/;
                if( ! r.test(item[key])){
                    item[key]="0.00"
                }else{
                    item[key]=item[key]
                }
            },
            isNumValue(event){
                //console.log(event);
                var reg = /^(-?[1-9]\d{0,5}\.\d{1,2}|-?0\.\d{1,2}|-?[1-9]\d{0,5}|0)/;
                if(reg.test(event.target.value)){
                    event.target.value = event.target.value.match(reg)[0]
                }else{
                    event.target.value = 0
                }
            },

            changeMoney(val){
              console.log(val);
               if(val){
                   var sum = 0;
                   for(let i=0;i<this.tableData.length;i++){
                       data = this.tableData[i];
                       data.realamount=0;
                       sum += data.arrAmount*1;
                   }
                   if(val>sum){
                       this.$message({
                           type: 'warning',
                           message: '输入金额大于应付总金额!'
                       });
                       this.amountSum = sum;
                   }
                   console.log(sum);
                   var data;
                   for(let i=0;i<this.tableData.length;i++){
                       console.log("金额 ： "+val);
                       data = this.tableData[i];
                       console.log(this.tableData[i]);
                      console.log(data.realamount);
                      console.log(data.youhuiamount);
                       if(val <= data.arrAmount){
                           data.realamount = val;

                           // if(data.goodsStatus.key=='PURCHASE'){
                           //     data.arrearAmount = data.arrearAmount*(-1);
                           // }
                           break;
                       }else {
                           data.realamount = data.arrAmount*1;
                           console.log("金额 ："+data.realamount);
                           val = val-data.arrAmount;
                           console.log("剩余金额 ： "+val);
                           // if(data.goodsStatus.key=='PURCHASE'){
                           //     data.arrearAmount = data.arrearAmount*(-1);
                           // }
                           continue;
                       }

                   }
               }
            },
            isDouble(item,key){
                var isNum=/^[+-]?(?:\d+|\d{1,3}(?:,\d{3})+)(?:\.\d+)?$/
                //console.log(isNum.test(item[key]));
                if(!isNum.test(item[key])){
                    item[key]="0.00"
                }else{
                    item[key]=item[key]
                }
            },
            cleanSearch(){
                this.currentPage=1;
                this.input="";
                this.inputValue=this.input;
                this.initData();
            },
            search(){
                var search = "";
                if(this.supplier){
                    search = "search.supplierId_eq="+this.supplier+"&"+search;
                }else {
                    this.$message({
                        message: '请选择供应商',
                        type: 'warning'
                    });
                    return;
                }
                if(this.documentType){
                    search = "search.goodsStatus_eq="+this.documentType+"&"+search;
                }
                if(this.createAt_st!=""){
                    //console.log(this.createAt_st);
                    search="search.createAt_gte="+this.createAt_st+" 00:00:00&"+search;
                }
                if(this.createAt_et!=""){
                    search="search.createAt_lte="+this.createAt_et+" 23:59:59&"+search;
                }
                if(!search){
                   return;
                }
                this.$axios.get("paymentBills/create?"+search).then(function(data){
                    if(data.status==200){
                        this.suppliers = data.content.suppliers;
                        this.purchasers = data.content.purchasers;
                        if(data.content.orders && data.content.orders.length>0){
                            for(let i=0;i<data.content.orders.length;i++){
                                data.content.orders[i].realamount=0;
                                data.content.orders[i].youhuiamount=0
                            }
                            this.tableData=data.table;
                        }
                        this.tableData = data.content.orders;
                    }else{
                        this.$message.error(data.message);
                    }
                })
            },
            getEntryTime(val){
                this.createAt_st=val;
            },
            getEntryTime1(val){
                this.createAt_et=val;
            },
            printNum(event){
                event.currentTarget.select();
            },
            getSummaries(param) {
                const { columns, data } = param;
                const sums = [];
                columns.forEach((column, index) => {
                    if (index === 0) {
                        sums[index] = '合计';
                        return;
                    }
                    if(index === 1 || index===2 || index === 3 || index===8){
                        sums[index] = '';
                        return;
                    }
                    const values = data.map(item => Number(item[column.property]));
                    if (!values.every(value => isNaN(value))) {
                        sums[index] = values.reduce((prev, curr) => {
                            const value = Number(curr);
                            if (!isNaN(value)) {
                                return prev + curr;
                            } else {
                                return prev;
                            }
                        }, 0);
                        sums[index] += '';
                    } else {
                        sums[index] = '';
                    }
                });
                return sums;
            },
            /*用户选择提示框后处理*/
            dialogResult(param){
                this.dialogIsShow=param.close;
                if(param.choose==="ok"){
                    //console.log("确定");
                    this.tableData.splice(this.curDataIndex,1);
                    this.$message({
                        type: 'success',
                        message: '删除成功!'
                    });
                }else if(param.choose==="cancel"){
                    //console.log("取消");
                }else{
                    //console.log("不做处理");
                }
            },
            handleDelete(index, row) {
                this.curDataPkId = row.id;
                this.curDataIndex = index;
                this.dialogIsShow = true;
                return false;
            },


        }
    }
</script>
<style scoped>
    @media (min-width:1198px) and (max-width: 1620px){
        .el-col-lg-5 {
            width: 30%;
        }
        .el-col-lg-3{
            width: 20%;
        }
    }
    @media(min-width:763px) and (max-width: 824px){
        .el-col-lg-5 {
            width: 100%;
        }
        .el-col-lg-3{
            width: 100%;
        }

    }
    @media(min-width:989px) and (max-width: 1901px){
       .el-col-md-8 {
            width: 40%;
        }
    }

</style>
